<template xmlns="http://www.w3.org/1999/html">


  <div style="height: 100%">
    <div class="homework-detail-content" v-if="homework">
      <h2>{{ homework.subject }}</h2>
      <div class="homework-content" v-html="homework.content"></div>
      <div style="margin-bottom: 20px">
        <span style="font-size: 14px;">截止日期:{{homework.finishdate}}</span>
      </div>

      <div class="homework-info">
        <span>老师：{{ homework.teacherName }}</span>

        <span class="homework-date">日期：{{ formatDate(homework.time) }}</span>
      </div>
    </div>
    <!-- 作业内容编辑区和图片上传区 -->
    <div v-if="studentHomeworkDetails">
      <Col style="border: 2px solid #9caf70; /* 边框颜色 */
       border-radius: 8px; /* 边框圆角 */
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
      padding: 20px; margin: 10px 20px;">
        <!-- 作业内容文本输入 -->
        <textarea
            class="homework-submission-text"
            v-model="submissionText"
            placeholder="在这里输入你的作业内容..."
            rows="6"
        ></textarea>

        <!-- 作业图片上传和预览 -->
        <div>
          <label

              style="font-size: 14px; cursor: pointer;"
              @click="resetHomework"
          >
          <img
              src="../../assets/images/reset.png"
              style="width: 30px; margin-left: 20px"
          />
         </label>

          <label
              for="file-upload"
              style="font-size: 14px; cursor: pointer;"
          >
            <img
                src="../../assets/images/photo.png"
                style="width: 32px; margin-left: 20px"
            />

          </label>
          <input
              type="file"
              id="file-upload"
              style="display: none;"
              @change="handleImageUpload"
          />
          <!-- 作业图片预览区域 -->
          <div class="image-preview-container">
            <img
                v-if="imagePreview"
                :src="imagePreview"
                alt="Image Preview"
                class="image-preview"
            />
          </div>
        </div>
      </Col>
    </div>

    <!-- 提交按钮 -->
    <button @click="submitHomework" class="homeworksubmit">提交作业</button>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { Col,Toast} from 'vant';
import axios from 'axios';
import { Local } from "@/utils/storage";
import {getOssPrefix} from "@/v-api/properties";
const prefix = getOssPrefix();
// 响应式引用
const homework = ref(null);
const homeworkId = ref(null);
const submissionText = ref('');
const submissionImageFile = ref(null);
const imagePreview = ref('');
const studentHomeworkDetails = ref(null); // 存储学生的作业详情
const userInfo = Local.get('userInfo')

onMounted(() => {
  const route = useRoute();
  const studentId =Local.get('userInfo').userId;
  const homeworkString = route.query.homework;
  const parsedHomework = homeworkString ? JSON.parse(homeworkString) : null;

  if (parsedHomework) {
    homework.value = parsedHomework;
    homeworkId.value = parsedHomework.homeworkId;
  }
  fetchHomeworkDetails(studentId, homeworkId.value);

});

// 格式化日期的函数
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

const handleImageUpload = event => {
  const file = event.target.files[0];
  if (file) {
    // 更新 imagePreview 用于显示预览
    imagePreview.value = URL.createObjectURL(file);
    // 更新 submissionImageFile 用于表单提交
    submissionImageFile.value = file;
  }
};

// 在 fetchHomeworkDetails 中打印获取的数据
const fetchHomeworkDetails = (studentId, homeworkId) => {
  axios.get(`/api/homework/completionStatus/${studentId}/${homeworkId}`)
      .then(response => {
        const details = response.data;
        if (details) {
          studentHomeworkDetails.value = details;
          submissionText.value = details.homeworkDetails || ''; // 使用 || 为 undefined 提供默认值
          imagePreview.value = details.homeworkUrl ? prefix + details.homeworkUrl : '';
        } else {
          // 处理数据为空的情况
        }
      })
      .catch(error => {
        console.error("Error fetching homework details:", error);

      });
};



// 提交作业的函数
const submitHomework = () => {
  const submissionData = new FormData();
  submissionData.append('homeworkId', homeworkId.value);
  submissionData.append('text', submissionText.value);
  // 用户选择了文件才添加到FormData
  if (submissionImageFile.value) {
    submissionData.append('image', submissionImageFile.value);
  }

  axios.post('/api/homework/submitHomework', submissionData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },

  })
      .then(response => {

        Toast.success("提交成功")
      })
      .catch(error => {
        // 无论是请求没有发出还是服务器没有响应，我们都在这里处理
        console.error("提交作业失败：", error.message);
        Toast.success("提交失败")
      });
};
// 重置作业内容和图片
const resetHomework = () => {
  // 清空文本输入
  submissionText.value = '';

  // 清除图片文件和预览
  submissionImageFile.value = null; // 清除文件数据
  imagePreview.value = ''; // 清除图片预览

  // 清除文件输入字段的值，这会取消选择文件
  const fileInput = document.getElementById('file-upload');
  fileInput.value = null; // 使用null来清空文件输入
};
</script>
<style scoped>


.homework-detail-content {
  border: 2px solid #9caf70; /* 边框颜色 */
  border-radius: 8px; /* 边框圆角 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  padding: 20px;
  border-radius: 8px; /* 圆角边框 */
  height: 20%;
  margin-right: 15px;
  margin-left: 15px;
}

h2 {
  margin: 0 0 10px; /* 标题的外边距 */
  font-size: 16px; /* 标题字体大小 */
  margin-left: 15px;

}

.homework-content {
  white-space: pre-wrap; /* 保留空白符序列，允许换行 */
  word-wrap: break-word; /* 长单词或不截断的单词将换行 */
  margin-bottom: 8px; /* 内容与下方信息的间距 */
  font-size: 12px;
}

/* 作业信息样式 */
.homework-info {
  font-size: 12px; /* 信息字体大小 */
  color: #666; /* 信息字体颜色 */
  margin-bottom: 5px; /* 信息与日期的间距 */

}

/* 格式化日期显示 */
.homework-date {
  font-size: 10px; /* 日期字体大小 */
  color: #999; /* 日期字体颜色 */
  margin-left: 60px;
}



.homework-submission-text {
  width: 88%;
  padding: 20px;
  resize: vertical;
  font-size: 12px;
  height:100px;
  border: 2px solid #9caf70; /* 边框颜色 */
  border-radius: 8px; /* 边框圆角 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  padding: 20px;
}



.image-preview-container {
  margin-top: 10px;
  padding: 20px;
  text-align: center;
}

.image-preview {
  max-width: 80%;
  max-height: 100px;
  border-radius: 4px;
}

.homeworksubmit {
  background-color: rgba(165, 214, 63, 0.71);
  border: #cbf3bd;
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 16px;
  margin-left: 80px; /* 根据需要调整 */
  width: 50%; /* 根据需要调整宽度 */
  cursor: pointer; /* 鼠标悬停时显示手型图标 */
  transition: background-color 0.3s; /* 背景色变化的过渡效果 */
  margin-top: 5px;
}

.homeworksubmit:hover {
  background-color: rgba(165, 214, 63, 0.9);
}


</style>